package com.ultrapower.mapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;

import com.ultrapower.bean.AgentEventBean;
import com.ultrapower.buffer.Buffer;
import com.ultrapower.buffer.FixedBuffer;
import com.ultrapower.util.AgentEventType;
import com.ultrapower.util.BytesUtils;

/**
 * @author 
 */
public class AgentEventMapper implements RowMapper<List<AgentEventBean>> {

    @Override
    public List<AgentEventBean> mapRow(Result result, int rowNum) throws Exception {
        if (result.isEmpty()) {
            return Collections.emptyList();
        }
        
        List<AgentEventBean> agentEvents = new ArrayList<>();
        for (Cell cell : result.rawCells()) {
            byte[] qualifier = CellUtil.cloneQualifier(cell);
            final AgentEventType eventType = AgentEventType.getTypeByCode(BytesUtils.bytesToInt(qualifier, 0));
            if (eventType == null) {
                continue;
            }
            
            byte[] value = CellUtil.cloneValue(cell);
            final Buffer buffer = new FixedBuffer(value);
            
            final int version = buffer.readInt();
            switch (version) {
                case 0 :
                    final String agentId = buffer.readPrefixedString();
                    final long startTimestamp = buffer.readLong();
                    final long eventTimestamp = buffer.readLong();
                    final byte[] eventMessage = buffer.readPrefixedBytes();
                    final AgentEventBean agentEvent = new AgentEventBean(version, agentId, startTimestamp, eventTimestamp, eventType);
                    agentEvent.setEventBody(eventMessage);
                    agentEvents.add(agentEvent);
                    break;
                default :
                    break;
            }
        }
        
        return agentEvents;
    }

}
